﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IMLibrary.Controls;
using IMLibrary.Controls.Toolbox;
using IMLibrary.Controls.vtExtender;

using IMLibrary;
using IMLibrary.Security; 
using IMLibrary.BinaryPacket;
using P;

using OurMsg.Controls;
using Ourmsg.FileTransmit;
using Ourmsg.APPClient;
using Ourmsg.Enum;

namespace OurMsg
{
    public partial class FormMain : IMLibrary.Controls.ExControls.FormEx//Win8Form
    {
        #region 构造函数
        public FormMain()
        {
            InitializeComponent();
            
            this.ToolStrip1.FormBackColor = this.BackColor;
            this.ToolStrip1.ItemClicked +=  sharpToolStrip1_ItemClicked ;
             
            IniUsersListBox();//初始化用户列表

            IniMsgClient(); //初始化消息客户端

            pLogin.Cancel += (s, e) => Client.Disonnect();
            pLogin.Login += new PanelLogin.EventHandler(pLogin_Login);
            pLogin.Register +=  pLogin_Register ;
                
            this.FormClosing += new FormClosingEventHandler(FormMain_FormClosing);
            this.ButStatus.ShowTypeChanged += ButStatus_ShowTypeChanged;

            timerFlicker.Elapsed += TimerFlicker_Elapsed;
        }

        

        void pLogin_Register(object sender, EventArgs e)
        {
            this.Hide();
            if (RegisterForm == null || RegisterForm.IsDisposed)
            {
                RegisterForm = new FormCreateUser();
                RegisterForm.CreateMsgAfter += (s, r) =>
                    {
                        Client.UserRegister(r,Global.ServerIP,2015);
                    };
            }
            RegisterForm.ShowDialog ();
            if (RegisterForm.UserID != 0)
            {
                this.pLogin.setNewUserID(RegisterForm.UserID);
                this.Show();
            }
        }

        void sharpToolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case "创建群":
                    {
                        if (crForm == null || crForm.IsDisposed)
                            crForm = new FormCreateRoom();
                        crForm.Show();
                        crForm.Activate();
                    }
                    break;
                case "查找":
                    {
                        if (queryform == null || queryform.IsDisposed)
                        {
                            queryform = new FormQuery();
                            queryform.CreateMsgAfter += (s, q) => Client.Query(q); //查询满足条件的用户或群
                        }
                        queryform.Show(); queryform.Activate();
                    }
                    break;
            }
        }

        void pLogin_Login(object sender, EventArgs e)
        {
            Global.loginInfo.UserID = pLogin.loginInfo.UserID;
            Global.loginInfo.IsSavePassword = pLogin.loginInfo.IsSavePassword;
            Global.loginInfo.IsAutoLogin = pLogin.loginInfo.IsAutoLogin;
            Global.loginInfo.ShowType = pLogin.loginInfo.ShowType;
            Global.loginInfo.Password = pLogin.loginInfo.Password;

            Client.ReadyLogin(Global.loginInfo.UserID, Encryption.Decrypt3DES(Global.loginInfo.Password), Global.loginInfo.ShowType);
        }
        #endregion

        #region 字段
        /// <summary>
        /// 是否成功登录过
        /// </summary>
        bool IsSuccessLogin = false;
        /// <summary>
        /// 用户列表控件
        /// </summary>
        private IMLibrary.Controls.Toolbox.Toolbox toolboxUsers;
        /// <summary>
        /// 群列表控件
        /// </summary>
        private IMLibrary.Controls.Toolbox.Toolbox toolboxRooms;
      
        /// <summary>
        /// 
        /// </summary>
        MsgClient Client = new MsgClient(Global.ServerIP,Global.ServerPort);
         

        #region 闪烁图片
        System.Timers.Timer timerFlicker = new System.Timers.Timer(500);
        /// <summary>
        /// 闪烁图片
        /// </summary>
        private Image FlickerImage = null;  
        /// <summary>
        /// 空图
        /// </summary>
        private Icon FlickerNullIcon = Icon.FromHandle((new Bitmap(16, 16)).GetHicon());
        /// <summary>
        /// 是否空图
        /// </summary>
        private bool isNullImage = false; 
        #endregion

        /// <summary>
        /// 创建群窗口
        /// </summary>
        FormCreateRoom crForm = null;
        /// <summary>
        /// 注册新用户窗口
        /// </summary>
        FormCreateUser RegisterForm = null;
        /// <summary>
        /// 找人找群窗口
        /// </summary>
        FormQuery queryform = null;
        #endregion

        #region 窗体事件 
        #region 窗体加载事件
        private void Form2_Load(object sender, EventArgs e)
        {
            this.panelTitle.Visible = false;
            this.pLogin.Dock = DockStyle.Fill;
            this.pLogin.LoadLoginUsers();

            this.Width = 260;
            this.Top = (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2;
            this.Left = (Screen.PrimaryScreen.WorkingArea.Width - this.Width);

            Global.IniBaseGroup(toolboxUsers, toolboxRooms); // 初始化基本组

            Global.MsgClient = Client;
        } 
        #endregion

        #region 窗体关闭事件

        void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        { 
                Client.Disonnect(); 
        }
        #endregion

        #endregion

        #region 消息客户端
        /// <summary>
        /// 消息处理代理函数,可多线程操作UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private delegate void OnRecivedMsg(object sender, MsgClientEventArgs e);

        private void IniMsgClient()
        {
            Client.Disconnected += (s, e) => this.Invoke(new OnRecivedMsg(Client_Disconnected), s, e);
            Client.ConnectOutTime += (s, e) => this.Invoke(new OnRecivedMsg(Client_ConnectOutTime), s, e);
            Client.RecivedUserRegister += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedUserRegister), s, e);
            Client.Logined += (s, e) => this.Invoke(new OnRecivedMsg(Client_Logined), s, e);
            Client.LoginElse += (s, e) => this.Invoke(new OnRecivedMsg(Client_LoginElse), s, e);
            Client.LoginFailed += (s, e) => this.Invoke(new OnRecivedMsg(Client_LoginFailed), s, e);
            Client.RecivedBlacklists += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedBlacklists), s, e);
            Client.RecivedElseData += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedElseData), s, e);
            Client.RecivedFriendBaseInfos += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedFriendBaseInfos), s, e);
            Client.RecivedFriendPresences += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedFriendPresences), s, e);
            Client.RecivedGroups += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedGroups), s, e);
            Client.RecivedRoomBaseInfos += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRoomBaseInfos), s, e);
            Client.RecivedRoomFriendPresences += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRoomFriendPresences), s, e);
            Client.RecivedRoomGroups += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRoomGroups), s, e);
            Client.RecivedSystemMsg += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedSystemMsg), s, e);
            Client.RecivedUserMsg += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedUserMsg), s, e);
            Client.RecivedRoomMsg += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRoomMsg), s, e);
            Client.RecivedCreateRoom += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedCreateRoom), s, e);
            Client.RecivedRoomData += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRoomData), s, e);
            Client.RecivedSetRoomManger += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedSetRoomManger), s, e);
            Client.RecivedSetRoomUserCard += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedSetRoomUserCard), s, e);
            Client.RecivedSetRoomBaseInfo += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedSetRoomBaseInfo), s, e);
            Client.RecivedDelRoomUser += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedDelRoomUser), s, e);
            Client.RecivedQuitRoom += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedQuitRoom), s, e); 
            Client.RecivedQueryUsers += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedQueryUsers), s, e);
            Client.RecivedQueryRooms += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedQueryRooms), s, e);
            Client.RecivedRequestAddFriend += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRequestAddFriend), s, e);
            Client.RecivedDelFriend  += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedDelFriend), s, e);
            Client.RecivedInviteAddRoom += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedInviteAddRoom), s, e);
            Client.RecivedRequestAddRoom += (s, e) => this.Invoke(new OnRecivedMsg(Client_RecivedRequestAddRoom), s, e);
        }
         
        #endregion

        #region 收到请求加群事件
        void Client_RecivedRequestAddRoom(object sender, MsgClientEventArgs e)
        {
            var msg = e.Obj as InviteMsg;
            if (msg != null)
            {
                Global.AddRecMsgs(e.From, MsgType.requestAddRoom, imageListNotify.Images[3], msg);
                timerFlicker.Enabled = true;
            }
        }
        #endregion

        #region 收到添加好友邀请事件
        void Client_RecivedInviteAddRoom(object sender, MsgClientEventArgs e)
        {
            var msg = e.Obj as InviteMsg;
            if (msg != null)
            {
                Global.AddRecMsgs(e.From, MsgType.inviteAddRoom , imageListNotify.Images[3], msg);
                timerFlicker.Enabled = true;
            }
        }
        #endregion
          
        #region 收到添加好友邀请事件
        void Client_RecivedRequestAddFriend(object sender, MsgClientEventArgs e)
        {
            var msg = e.Obj as InviteMsg;
            if (msg != null)
            {
                Global.AddRecMsgs(e.From, MsgType.requestAddFriend,imageListNotify.Images[3], msg);
                timerFlicker.Enabled = true;
            }
        }
        #endregion

        #region 收到删除好友事件 
        void Client_RecivedDelFriend(object sender, MsgClientEventArgs e)
        {
            var user = Global.GetUser(e.From);
            if (user != null)
            {
                Global.TabFriend.Items.Remove(user.ToolboxItem);
                if (user.formTalk != null && !user.formTalk.IsDisposed)
                {
                    user.formTalk.Close(); user.formTalk.Dispose();
                }
                Global.DelUser(e.From);
            }
        }
        #endregion

        #region 收到查询群返回结果
        void Client_RecivedQueryRooms(object sender, MsgClientEventArgs e)
        {
            if (queryform != null && !queryform.IsDisposed)
                queryform.AddQueryRoos(e.Obj as List<QueryRoom >);
        }
        #endregion

        #region 收到查询用户返回结果
        void Client_RecivedQueryUsers(object sender, MsgClientEventArgs e)
        {
            if (queryform != null && !queryform.IsDisposed)
                queryform.AddQueryUsers(e.Obj as List<QueryUser>);
        }
        #endregion

        #region 群基本信息更新成功事件
        void Client_RecivedSetRoomBaseInfo(object sender, MsgClientEventArgs e)
        {
            RoomBaseInfo rbinfo = e.Obj as RoomBaseInfo;
            var roomID = rbinfo.RoomID;
            if (rbinfo != null)
            {
                var r = Global.GetRoom(roomID);
                if (r != null)
                {
                    r.BaseInfo.RoomName = rbinfo.RoomName;
                    r.BaseInfo.Notice = rbinfo.Notice;
                    r.BaseInfo.Remark = rbinfo.Remark;
                    r.BaseInfo.AddCondition = rbinfo.AddCondition;
                    
                    var frm = Global.GetFormSetRoom(roomID);
                    if (frm != null)
                        frm.SetRoomBaseInfo(rbinfo);

                    var f = Global.GetRoomTalkForm(roomID);
                    if (f != null)
                        f.SetRoomBaseInfo(rbinfo);
                }
            }
        }
        #endregion

        #region 收到成功设置群用户名片消息
        void Client_RecivedSetRoomUserCard(object sender, MsgClientEventArgs e)
        {
            RoomUser rUser = e.Obj as RoomUser;
            var roomID = rUser.RoomID;
            if (rUser != null)
            {
                var ru = Global.GetRoomUser(roomID, rUser.UserID);
                if (ru != null)
                {
                    ru.UserCard = rUser.UserCard;

                    var frm = Global.GetFormSetRoom(roomID);
                    if (frm != null)
                        frm.SetRoomUserCard(rUser.UserID, rUser.UserCard);

                    var f = Global.GetRoomTalkForm(roomID);
                    if (f != null)
                    {
                        f.SetUserCard(ru.UserID, ru.UserCard); 
                    }
                }
            }
        }
        #endregion

        #region 收到成功删除群用户消息
        void Client_RecivedDelRoomUser(object sender, MsgClientEventArgs e)
        {
            RoomUser rUser = e.Obj as RoomUser;
            var roomID = rUser.RoomID;

            if (rUser != null)
            {
                var r = Global.GetRoom(roomID);
                if (r != null)
                { 
                        var frm = Global.GetFormSetRoom(roomID);
                        if (frm != null)
                            frm.DelRoomUser(rUser.UserID);

                        var f = Global.GetRoomTalkForm(roomID);
                        if (f != null)
                        {
                            //f.AddSystemMsg(string.Format("{0}({1}) 已被管理员 {2}({3}) 请出群.",
                            //    Global.GetRoomUser(roomID, rUser.UserID).UserName, rUser.UserID, Global.GetRoomUser(roomID, e.From).UserName, e.From));
                            f.DelUser(rUser.UserID);
                        }
                        r.DelUser(rUser.UserID);
                }
            }
        }
        #endregion

        #region 退出群事件
        private void Client_RecivedQuitRoom(object sender, MsgClientEventArgs e)
        {
            RoomUser rUser = e.Obj as RoomUser;
            if (rUser == null) return;
            var roomID = rUser.RoomID;
            var r = Global.GetRoom(roomID);
            if (r != null)
            {
                Global.TabMyRoom.Items.Remove(r.ToolboxItem);
                if (r.formTalk != null && !r.formTalk.IsDisposed)
                {
                    r.formTalk.Close(); r.formTalk.Dispose();
                }
                Global.DelRoom(roomID);
            }
        }
        #endregion

        #region 收到成功设置群管理员消息
        void Client_RecivedSetRoomManger(object sender, MsgClientEventArgs e)
        {
            RoomUser rUser = e.Obj as RoomUser;
            var roomID = rUser.RoomID;

            if (rUser != null)
            {
                var ru = Global.GetRoomUser(roomID, rUser.UserID);
                if (ru != null)
                {
                    ru.Admin  = rUser.Admin;

                    var frm = Global.GetFormSetRoom(roomID);
                    if (frm != null)
                        frm.SetRoomManager(rUser.UserID, rUser.Admin);

                    var f = Global.GetRoomTalkForm(roomID);
                    if (f != null)
                    {
                        f.SetManager(ru.UserID, ru.Admin);
                        //if (rUser.Admin)
                        //    f.AddSystemMsg(string.Format("{0}({1}) 已被 {2}({3}) 设置为管理员.",
                        //        ru.UserName, rUser.UserID, Global.GetRoomUser(roomID, e.From).UserName, e.From));
                        //else
                        //    f.AddSystemMsg(string.Format("{0}({1}) 已被 {2}({3}) 取消了管理员权限.", 
                        //        ru.UserName, rUser.UserID, Global.GetRoomUser(roomID, e.From).UserName, e.From));
                    }
                }
            }
        }
        #endregion

        #region 收到创建群服务器的响应
        void Client_RecivedCreateRoom(object sender, MsgClientEventArgs e)
        {
            if (crForm != null)
            {
                crForm.RoomID = e.From;
                crForm.IsReturn = true;
            }
        }
        #endregion

        #region 收到好友消息
        void Client_RecivedUserMsg(object sender, MsgClientEventArgs e)
        {
            var element = e.Obj as P.Element;
            if (element == null) return;
            var user = Global.GetUser(e.From);
            if (user == null)
                user =Global. AddStranger( element.From,element.FromName,element.FromHeadID );

            if (e.Obj is P.Message)
            {
                var msg = e.Obj as P.Message;
                if (user.formTalk == null || user.formTalk.IsDisposed)
                {
                    user.ToolboxItem.HaveMessage = true;
                    FlickerImage = user.ToolboxItem.NotSelectedImage;
                    Global.AddRecMsgs(user.UserID, MsgType.userMsg, user.ToolboxItem.NotSelectedImage, user);
                    OpeRecordDB.AddMsg(msg, MsgType.userMsg, e.From, e.To);
                    timerFlicker.Enabled = true;//闪烁图标
                }
                else
                {
                    user.formTalk.AddMsg(msg);
                    OpeRecordDB.AddMsg(msg, MsgType.userMsg, e.From, e.To, true);
                }
            }
            else if (e.Obj is P.FileMsg)
            {
                var msg = (P.FileMsg)e.Obj;
                var frm = Global.ShowTalkForm(user);
                frm.ReciveFileMsg(msg);
            }
            else if (e.Obj is P.ImageFileMsg)
            {
                var msg = (P.ImageFileMsg)e.Obj;
                System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(Global.loginInfo.UserID + "\\ArrivalImage");
                if (!dInfo.Exists)
                    dInfo.Create();
                string fileName = Global.loginInfo.UserID + "\\ArrivalImage\\" + msg.MD5 + ".gif";
                if (System.IO.File.Exists(fileName)) return;//如果本地已经有此文件已经存在，则退出(不接收文件)
                TFileInfo fileinfo = new TFileInfo(msg.MD5, msg.Extension);
                fileinfo.fullName = fileName;
                fileinfo.Length = msg.Length;
                 
                {
                    #region UDP传输图片
                    var  imageUdpClient = new ImageClientV1(fileinfo, Global.ServerIP, Global.ImageServerUdpPort, false, true);
                    imageUdpClient.Transmitted += (s1, e1) =>
                    {
                        if (user.formTalk != null && !user.formTalk.IsDisposed)
                        {
                            imageUdpClient.Dispose();
                            var image = Image.FromFile(fileName);
                            user.formTalk.UpdateImage(msg.MD5, image);
                        }
                    }; 
                    #endregion
                }
            }
            else if (e.Obj is P.RemoteHelp)
            {
                var msg = (P.RemoteHelp)e.Obj;
                if (msg.OprType == OprationType.New)
                {
                    Global.ShowTalkForm(user).SetRemoteHelp(msg);
                }
                else if (user.formTalk != null && !user.formTalk.IsDisposed)
                {
                    user.formTalk.SetRemoteHelp(msg);
                }
            }
            else if (e.Obj is P.AVMsg)
            {
                var msg = (P.AVMsg)e.Obj;
                if (msg.OprType == OprationType.New)
                {
                    Global.ShowTalkForm(user).SetAVControl(msg);
                }
                else if (user.formTalk != null && !user.formTalk.IsDisposed)
                {
                    user.formTalk.SetAVControl(msg);
                }
            }
        } 
        #endregion

        #region 收到系统消息
        void Client_RecivedSystemMsg(object sender, MsgClientEventArgs e)
        {

        }
        #endregion

        #region 收到群消息
        void Client_RecivedRoomMsg(object sender, MsgClientEventArgs e)
        { 
            if (e.Obj is P.Message)
            {
                var msg = (P.Message)e.Obj;

                var r = Global.GetRoom(msg.RoomID);
                if (r == null) return;

                if (r.formTalk == null || r.formTalk.IsDisposed)
                {
                    r.ToolboxItem.HaveMessage = true;
                    FlickerImage = r.ToolboxItem.NotSelectedImage;
                    Global.AddRecMsgs(r.BaseInfo.RoomID, MsgType.roomMsg, r.ToolboxItem.NotSelectedImage, r);
                    OpeRecordDB.AddMsg(msg, MsgType.roomMsg, e.From, r.BaseInfo.RoomID);
                    timerFlicker.Enabled = true;//闪烁图标
                }
                else
                {
                    r.formTalk.AddMsg(msg);
                    OpeRecordDB.AddMsg(msg, MsgType.roomMsg, e.From, r.BaseInfo.RoomID, true);
                }
            }
            else if (e.Obj is P.ImageFileMsg)
            {
                var msg = (P.ImageFileMsg)e.Obj;
                var r = Global.GetRoom(msg.RoomID);
                if (r == null) return;

                System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(Global.loginInfo.UserID + "\\ArrivalImage");
                if (!dInfo.Exists)
                    dInfo.Create();
                string fileName = Global.loginInfo.UserID + "\\ArrivalImage\\" + msg.MD5 + ".gif";
                if (System.IO.File.Exists(fileName))
                    return;//如果本地已经有此文件已经存在，则退出(不接收文件)

                TFileInfo fileinfo = new TFileInfo(msg.MD5, msg.Extension);
                fileinfo.fullName = fileName;
                fileinfo.Length = msg.Length;
                 
                {
                    #region UDP传输图片
                    var imageUdpClient = new ImageClientV1(fileinfo, Global.ServerIP, Global.ImageServerUdpPort, false, true);
                    imageUdpClient.Transmitted += (s1, e1) =>
                    {
                        if (r.formTalk != null && !r.formTalk.IsDisposed)
                        {
                            var image = Image.FromFile(fileName);
                            r.formTalk.UpdateImage(msg.MD5, image);
                            imageUdpClient.Dispose();
                        }
                    }; 
                    #endregion
                }
            }
        }
        #endregion

        #region 收到群分组
        void Client_RecivedRoomGroups(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is  RoomGroup)
                    {
                        var g = obj as  RoomGroup;
                        var group = Global.GetRoomGroup(g.GroupID);
                        var isExsit = true;

                        ///如果分组不存在
                        if (group == null)
                        {
                            group = new ExGroup();
                            isExsit = false;
                        }

                        group.GroupID = g.GroupID;
                        group.GroupName = g.GroupName;
                        group.IsSystem = g.IsSystem;
                        group.IsDel = false;

                        ///如果分组不存在
                        if (!isExsit)
                        {
                            Toolbox.Tab tab = null;
                            if (Global.AddRoomGroupForm != null)
                                Global.AddRoomGroupForm.GroupName = group.GroupName;
                                
                            tab = toolboxRooms.AddGroup(group.GroupName);

                            tab.Tag = group;
                            tab.FlickerIcons();
                            group.ToolboxTab = tab;
                            Global.RoomGroups.Add(group.GroupID, group);
                        }
                    }
        }
        #endregion

        #region 收到群用户在线状态
        void Client_RecivedRoomFriendPresences(object sender, MsgClientEventArgs e)
        {

        }
        #endregion

        #region 收到群基本信息
        void Client_RecivedRoomBaseInfos(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is RoomBaseInfo)
                    {
                        var r = obj as RoomBaseInfo;

                        var room = Global.GetRoom(r.RoomID);
                        var isExsit = true;

                        if (room == null)
                        {
                            room = new ExRoom();
                            isExsit = false;
                        }

                        room.BaseInfo.RoomID = r.RoomID;
                        room.BaseInfo = r;

                        Image image = Global.GetHeadImage("Room", ImageSize.P32X32);
                        Image smallImage = Global.GetHeadImage("Room", ImageSize.P20X20);
                        var text = room.BaseInfo.RoomName;
                        var item = new Toolbox.Item(text);
                        item.Image = smallImage;
                        item.NotSelectedImage = smallImage; item.SelectedImage = image;
                        item.Tag = room;
                        item.IsOnline = true;

                        if (!isExsit)
                        {
                            Global.Rooms.Add(room.BaseInfo.RoomID, room);
                            room.ToolboxItem = item;
                            var g = Global.GetRoomGroup(room.BaseInfo.GroupID);
                            if (g != null)
                                g.ToolboxTab.Items.Add(item);
                            else
                                Global.TabMyRoom.Items.Add(item);
                        }
                    }
        }
        #endregion

        #region 收到联系人分组信息
        void Client_RecivedGroups(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is Group)
                    {
                        var g = obj as Group;
                        var group = Global.GetGroup(g.GroupID);
                        var isExsit = true;

                        ///如果分组不存在
                        if (group == null)
                        {
                            group = new ExGroup();
                            isExsit = false;
                        }

                        group.GroupID = g.GroupID;
                        group.GroupName = g.GroupName;
                        group.OrderID = g.OrderID;
                        group.SupGroupID = g.SupGroupID;
                        group.IsSystem = g.IsSystem;
                        group.IsDel = false;
                        ///如果分组不存在
                        if (!isExsit)
                        {
                            var tab = toolboxUsers.InsertGroup(group.GroupName, toolboxUsers.Categories.Count - 2);
                            tab.AllowDelete = false;
                            tab.AllowDrag = false;
                            tab.AllowDropItem = false;
                            tab.Tag = group;
                            group.ToolboxTab = tab;
                            Global.Groups.Add(group.GroupID, group);
                            tab.FlickerIcons(); 
                        }
                    } 
        }
        #endregion

        #region 收到好友在线状态
        void Client_RecivedFriendPresences(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is Presence)
                    {
                        var p = obj as Presence;
                        var user = Global.GetUser(p.UserID);
                        if (user != null)
                            user.ShowType = p.ShowType;
                    } 
        }
        #endregion

        #region 收到好友基本信息
        void Client_RecivedFriendBaseInfos(object sender, MsgClientEventArgs e)
        {
            Random r = new Random();
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is FriendBaseInfo)
                    {
                        var u = obj as FriendBaseInfo;
                        var user = Global.GetUser(u.UserID);
                        var isExsit = true;

                        if (user == null)
                        {
                            user = new ExUser();
                            isExsit = false;
                        }

                        user.UserID = u.UserID;
                        user.UserName = u.UserName;
                        user.HeadID = u.headID;
                        user.Signature = u.Signature;
                        user.RemarkName = u.RemarkName;
                        user.GroupID = u.GroupID;
                        user.OrderID = u.OrderID;
                        var HeadID = user.HeadID.ToString();
                        if (!isExsit)
                        {
                            Image image = Global.GetHeadImage(HeadID, ImageSize.P32X32);
                            Image smallImage = Global.GetHeadImage(HeadID, ImageSize.P20X20);
                            var text = user.RemarkName;
                            if (string.IsNullOrEmpty(text))
                                text = user.UserName;
                            var item = new Toolbox.Item(text);
                            item.Image = smallImage;
                            item.NotSelectedImage = smallImage; item.SelectedImage = image;
                            item.Signature = user.Signature;
                            item.Tag = user;
                            user.ToolboxItem = item;
                            Global.Users.Add(user.UserID, user);

                            var g = Global.GetGroup(user.GroupID);
                            if (g != null)
                                g.ToolboxTab.Items.Add(item);
                            else
                                Global.TabFriend.Items.Add(item);

                            user.ShowType = u.ShowType;
                        }
                    }
        }
        #endregion

        #region 收到其他数据
        void Client_RecivedElseData(object sender, MsgClientEventArgs e)
        {

        }
        #endregion

        #region 收到黑名单数据
        void Client_RecivedBlacklists(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                for (int i = 0; i < toolboxUsers.Categories.Count; i++)
                    if (toolboxUsers.Categories[i].FactText == "黑名单")
                    {
                        foreach (var obj in objects)
                            if (obj is UserBlacklist)
                            {
                                var u = obj as UserBlacklist;
                                Image image = Global.GetHeadImage("0", ImageSize.P32X32);
                                var item = new IMLibrary.Controls.Toolbox.Toolbox.Item(u.UserID.ToString(), image);
                                item.NotSelectedImage = Global.GetHeadImage("0", ImageSize.P16X16); item.SelectedImage = image;
                                item.Tag = u;
                                toolboxUsers.Categories[i].Items.Add(item);
                            }
                    }
        }
        #endregion

        #region 收到登录失败消息
        void Client_LoginFailed(object sender, MsgClientEventArgs e)
        {
            Global.ShowMessage("登录失败，帐号或密码错误！");
            pLogin.HideCanlePanel();
        }
        #endregion

        #region 收到帐号别处登录消息
        void Client_LoginElse(object sender, MsgClientEventArgs e)
        {
            Global.ShowMessage("此帐号在别处登录，您被强制下线！");
            pLogin.HideCanlePanel();
            pLogin.Visible = true;
            panelTitle.Visible = false;
        }
        #endregion

        #region 收到登录成功消息
        void Client_Logined(object sender, MsgClientEventArgs e)
        {
            var auth = e.Obj as Auth;
            if (auth != null)
            {
                Global.loginInfo.UserID = auth.UserID.ToString();
                Global.loginInfo.HeadID = auth.HeadID;
                Global.loginInfo.IsCustomHead = auth.IsCustomHead;
                Global.loginInfo.UserName = auth.UserName;

                Global.ImageServerTcpPort = auth.ImageFilePort;
                Global.ImageServerUdpPort = auth.ImageFilePort;
                Global.P2PServerPort = auth.P2pPort;
                Global.OfflineFileServerPort = auth.OfflineFilePort;

                OurMsg.OpeRecordDB.SaveAuth(Global.loginInfo);

                labelUserName.Text = auth.UserName + "(" + auth.UserID + ")";

                #region 判断登录的用户本地数据库文件夹是否存在
                System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(auth.UserID.ToString());
                if (!dInfo.Exists)
                    dInfo.Create();
                string FileNamePath = auth.UserID.ToString() + "\\Record.mdb";
                if (!System.IO.File.Exists(FileNamePath))
                    System.IO.File.Copy("Record.db", FileNamePath);

                ////初始化本地数据库连接字符串
                OurMsg.SQLiteData.SQLiteDBHelper.connectionString = "data source=" + FileNamePath;
                #endregion
            }

            IsSuccessLogin = true;
            this.ButStatus.Image = pLogin.ButStatus.Image;
            this.ButStatus.HeaderText = pLogin.ButStatus.HeaderText;
            this.ButStatus.Tag = pLogin.ButStatus.Tag;
            this.MyHeadBut.Image = pLogin.pictureBox1.Image;

            this.pLogin.Visible = false;
            this.panelTitle.Visible = true ;

        }
        #endregion

        #region 收到注册用户成功消息 
        void Client_RecivedUserRegister(object sender, MsgClientEventArgs e)
        {
            if (RegisterForm != null && !RegisterForm.IsDisposed)
            {
                UserRegister r=e.Obj as UserRegister ;
                if (r != null)
                {
                    RegisterForm.IsReturn = true;
                    RegisterForm.UserID = r.UserID;
                }
            }
        }
        #endregion

        #region 收到群数据（包括群用户信息）
        void Client_RecivedRoomData(object sender, MsgClientEventArgs e)
        {
            var objects = e.Obj as List<object>;
            if (objects != null)
                foreach (var obj in objects)
                    if (obj is RoomUser)
                    {
                        var user = obj as RoomUser;
                        Global.Rooms[user.RoomID].AddUser(user);
                        if (Global.Rooms[user.RoomID].formTalk != null && !Global.Rooms[user.RoomID].formTalk.IsDisposed)
                            Global.Rooms[user.RoomID].formTalk.addUser(user);
                    }
        }
        #endregion

        #region 连接服务器超时
        void Client_ConnectOutTime(object sender, MsgClientEventArgs e)
        {
            Global.ShowMessage("连接服务器超时，请检查网络是否正常！");
            pLogin.HideCanlePanel();
        }
        #endregion

        #region 连接断开事件
        void Client_Disconnected(object sender, MsgClientEventArgs e)
        {
            //Global.ShowMessage("网络已断开，请检查网络是否正常！");
            if (!IsSuccessLogin)
            {
                pLogin.HideCanlePanel();
                pLogin.Visible = true;
            }
            else
            {
                ButStatus.SetShowType(ShowType.Offline);
                Global.SetAllUsersOffline();
            }
        }
        #endregion

        #region 联系人和群组列表控件
        private void IniUsersListBox()
        {
            toolboxUsers = new IMLibrary.Controls.Toolbox.Toolbox(false);
            toolboxUsers.DragItemBefore += new  Toolbox.DragItemBeforeEventHandler(toolboxUsers_DragItemBefore);
            toolboxUsers.DoubleClick += (s, e) =>
                {
                    if (toolboxUsers.SelectedItem != null)
                    {
                        var item = toolboxUsers.SelectedItem;
                        var u = item.Tag as ExUser;
                        if (u != null)
                            Global.ShowTalkForm(u); 
                    }
                };
            tabPageEx1.Controls.Add(toolboxUsers);
            toolboxUsers.IniListBox();
            toolboxUsers.ItemHeight = toolboxUsers.SelectItemHeight;
            toolboxRooms = new  Toolbox(false);
            toolboxRooms.DoubleClick += (s, e) =>
                {
                    if (toolboxRooms.SelectedItem != null)
                    {
                        var item = toolboxRooms.SelectedItem;
                        var r = item.Tag as ExRoom ;
                        if (r != null)
                            Global.ShowTalkForm(r); 
                    }
                };
            tabPageEx2.Controls.Add(toolboxRooms);
            toolboxRooms.IniListBox();
        }

        void toolboxUsers_DragItemBefore(object sender, IMLibrary.Controls.Toolbox.ToolboxEventArgs e)
        {
            if (e.Tab != null)
            {
                {
                    var g = e.Tab.Tag is ExGroup ? (ExGroup)e.Tab.Tag : new ExGroup();
                    if (g.GroupID == -10)
                        if (MessageBox.Show("确定要将用户移至黑名单吗？", "提示",
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3) == System.Windows.Forms.DialogResult.Yes)
                        {

                        }
                        else
                            e.Cancel = true;//取消移动
                }

                {
                    var tab = e.Item.Owner as Toolbox.Tab;
                    var g = tab.Tag is ExGroup ? (ExGroup)tab.Tag : new ExGroup();
                    if (g.GroupID == -10)
                        if (MessageBox.Show("确定要将用户从黑名单添加为好友吗？", "提示",
                                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3) == System.Windows.Forms.DialogResult.Yes)
                        {

                        }
                        else
                            e.Cancel = true;//取消移动
                }
            }
        }
        #endregion

        #region 更改在线状态按键事件
        void ButStatus_ShowTypeChanged(object sender, EventArgs e)
        {
            if (this.ButStatus.ShowType != ShowType.Offline)
            {
                if (!Client.IsConnection   )
                    Client.ReadyLogin(Global.loginInfo.UserID, Encryption.Decrypt3DES(Global.loginInfo.Password), ButStatus.ShowType);
                else
                    Client.SetChangeShowType(this.ButStatus.ShowType);
            }
            else
                Client.Disonnect();
        }
        #endregion

        #region 闪烁系统栏图标

        private void TimerFlicker_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Global.RecMsgs.Count > 0)
            {
                if (isNullImage)
                {
                    this.notifyIcon1.Icon = FlickerNullIcon; isNullImage = false;
                }
                else
                {
                    this.notifyIcon1.Icon = Global.RecMsgs[0].image; isNullImage = true;
                }
            }
            else
            {
                this.notifyIcon1.Icon = Properties.Resources.community;
                timerFlicker.Enabled = false;//停止闪烁图标
            }
        }
         
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (Global.RecMsgs.Count > 0)
            {
                switch (Global.RecMsgs[0].msgType)
                {
                    case MsgType.requestAddFriend:
                        {
                            var frm = new FormRespondAddFriendorRoom(FormRespondAddFriendorRoom.AddType.RequestAddFriend, Global.RecMsgs[0].Tag as InviteMsg);
                            frm.Show(); frm.Activate();
                            Global.RecMsgs.Remove(Global.RecMsgs[0]);
                        }
                        break;
                    case MsgType.inviteAddRoom :
                        {
                            var frm = new FormRespondAddFriendorRoom(FormRespondAddFriendorRoom.AddType.InviteAddRoom, Global.RecMsgs[0].Tag as InviteMsg);
                            frm.Show(); frm.Activate();
                            Global.RecMsgs.Remove(Global.RecMsgs[0]);
                        }
                        break;
                    case MsgType.requestAddRoom :
                        {
                            var frm = new FormRespondAddFriendorRoom(FormRespondAddFriendorRoom.AddType.RequestAddRoom, Global.RecMsgs[0].Tag as InviteMsg);
                            frm.Show(); frm.Activate();
                            Global.RecMsgs.Remove(Global.RecMsgs[0]);
                        }
                        break;
                    case MsgType.userMsg:
                        {
                            var u = Global.GetUser(Global.RecMsgs[0].ID);
                            if (u != null)
                                Global.ShowTalkForm(u);
                        }
                        break;
                    case MsgType.roomMsg:
                        {
                            var r = Global.GetRoom(Global.RecMsgs[0].ID);
                            if (r != null)
                                Global.ShowTalkForm(r);
                        }
                        break;
                }
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (RegisterForm != null && !RegisterForm.IsDisposed)//如果注册新用户窗口不为空
            {
                RegisterForm.Show();//显示注册新用户窗口
                RegisterForm.Activate();
            }
            else//否则显示主窗口
            {
                this.WindowState = FormWindowState.Normal;
                this.TopMost = true;
                this.Show();
            }
        }
        #endregion
        
    }
}
